package com.feng.study.controller;

import com.alibaba.fastjson.JSON;
import com.feng.study.value.User;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.stream.Collectors;

@RestController
@Slf4j
public class CacheDemo {

    private final static Cache<Integer, Integer> INTEGER_CACHE = CacheBuilder.newBuilder()
            .initialCapacity(1).maximumSize(1).expireAfterWrite(10, TimeUnit.SECONDS).build();

    @RequestMapping(value = "/cache/demo",method = RequestMethod.GET)
    @Cacheable(value = "cacheDemo",sync = true)
    public String cacheDemo(String cacheId){
        List<Integer> list = Lists.newArrayList(1,2,3,4,1,1,1);
        Consumer<Integer> consumer= new Consumer<Integer>() {
            @Override
            public void accept(Integer integer) {
                int a=integer+2;
                System.out.println(a);
            }
        };
        List<Integer> collect = list.stream().peek(p -> log.info("链表值:{}",p+10)).collect(Collectors.toList());

        User user = new User();
        user.setAge(11).setName(cacheId).setGender("nan");
        String s = JSON.toJSONString(user);
        return JSON.toJSONString(user);
    }

    @GetMapping(value = "/cache/demo02")
    public String cacheLocal(){
        testGet02();
        testGet02();
        return "";
    }

    public static void main(String[] args) {
        testGet01();
    }

    /**
     * get()方法，当对于get++put
     */
    private static void testGet01(){
        try {
            Integer integer = INTEGER_CACHE.get(1, new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    return 19;
                }
            });
            System.out.println(integer);
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
    private void testGet02(){
        try {
            Integer integer = INTEGER_CACHE.get(1, this::getValue);
            System.out.println(integer);
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    private Integer getValue(){
        //获取值
        return 20;
    }
}
